package com.roc.web.action.windcontroll;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TblJumpMchtInf;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.JumpMchtService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MccGroup;
import com.roc.util.constant.Role;
/**
 * 自选商户开通
 * @author 160711BB
 *
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/perfectBill")
public class JumpMchtAction extends PaginationBaseAction{
	
	private Logger logger = LogManager.getLogger(PaginationBaseAction.class);
	
	@Autowired
	private IPageService pagenitionService;
	
	@Autowired
	private JumpMchtService jumpMchtService;
	
	private JumpMchtSearchCondition searchCondition;
	
	
	private TblJumpMchtInf tjm;
	
	private String openMchtCd;
	
	private String openStatus;
	
	private TblJumpMchtInf detail;
	
	/**
	 * 自选商户开通入口
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/windControllSta/jumpMchtJsp.jsp")/*,
			@Result(name ="addOrUpdateJspInit", type = "chain", location = "addOrUpdateJspInit")*/,
			@Result(name = "error", location = "/error.jsp")})
	public String jspInit(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.AGENT.getCode()) || op.getRoleType().equals(Role.O_MANAGER.getCode())) {
			return SUCCESS;
		}
		
		/*if(Role.MERCHANT.getCode().equals(op.getRoleType())){
			return "addOrUpdateJspInit";
		}*/
		addActionError("无权限访问!!!");
		return ERROR;
	}
	
	/**
	 * 查询可开通自选商户功能商户
	 * @return
	 */
	@Action(value = "queryJumpMchtList", results = { @Result(name = "success", location = "/pages/windControllSta/jumpMchtJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryJumpMchtList(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if (searchCondition == null) {
			searchCondition = (JumpMchtSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new JumpMchtSearchCondition();
			}
		}
		
		try {
			
			if(Role.AGENT.getCode().equals(logingMerchant.getRoleType()) || Role.O_MANAGER.getCode().equals(logingMerchant.getRoleType())){
				
				String agentId= String.valueOf(logingMerchant.getId());
				searchCondition.setAgentId(agentId);
				
			}else{
				addActionError("无权限访问!!!");
				return ERROR;
			}
			int rows = pagenitionService.countSQL(searchCondition);
			List<TblJumpMchtInf> rsList = new ArrayList<TblJumpMchtInf>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList,rsList);
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, rsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error("自选商户开通商户信息查询异常");
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 商户登录页面初始化
	 * @return
	 */
	@Action(value = "addOrUpdateJspInit", results = { @Result(name = "success", location = "/pages/windControllSta/jumpMchtDetailJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String addOrUpdateJspInit(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			tjm = jumpMchtService.queryJumpMchtDetail(logingMerchant.getAccountNo());
			getRequest().setAttribute("mccGroupMap", MccGroup.getAllEnumMap());
		} catch (Exception e) {
			logger.error("查询自选商户开通详情异常");
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 申请开通自选商户功能
	 * @return
	 */
	@Action(value = "saveJumpMchtInf", results = { @Result(name = "success",type="chain", location = "addOrUpdateJspInit"),
			@Result(name = "validateFourElem", location = "/pages/windControllSta/validateFourElem.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String saveJumpMchtInf(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String,Object> resMap = jumpMchtService.saveOrUpdateJumpMchtInf(tjm, logingMerchant);
			 
			if(!Boolean.parseBoolean(resMap.get("flag").toString())){//未进行四要素验证
				detail = jumpMchtService.queryFourEleDetail(String.valueOf(logingMerchant.getAccountNo()));
				getRequest().setAttribute("detail", detail);
				addActionMessage((String) resMap.get("msg"));
				return "validateFourElem";
			}
			addActionMessage((String) resMap.get("msg"));
		} catch (Exception e) {
			addActionMessage("保存自选商户开通异常");
			logger.error("保存自选商户开通失败",e);
		}
		return SUCCESS;
	}
	
	/**
	 * 四要素验证
	 * @return
	 */
	@Action(value = "saveFourEleForm", results = {@Result(name = "success",type="chain", location = "addOrUpdateJspInit"),
			@Result(name = "error", location = "/error.jsp")})
	public String saveFourEleForm(){
		
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String,Object> resMap = jumpMchtService.saveFourEleForm(detail, logingMerchant);
			addActionMessage((String) resMap.get("msg"));
		} catch (Exception e) {
			addActionMessage("四要素验证异常");
			logger.error("四要素验证失败："+e);
		}
		return SUCCESS;
		
	}
	
	/**
	 * 修改自选商户开通状态
	 * @return
	 */
	@Action(value = "openOrClosePerfectBill",results = {@Result(name = "error", location = "/error.jsp")})
	public String openOrClosePerfectBill(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String,Object> resMap = new HashMap<String, Object>();
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		
		try {
			out = response.getWriter();
			resMap = jumpMchtService.modifyPerfectBillStatus(openMchtCd, openStatus, logingMerchant);
			jsonObject.put("resMap", resMap);
			out.print(jsonObject.toString());
			
		} catch (Exception e) {
			addActionMessage("修改自选商户开通状态异常");
			logger.error("修改自选商户开通状态失败：",e);
		}
		
		if(out != null){
			out.flush();
			out.close();
		}
		
		return null;
	}

	private void dealWithTheListSpecially(List<Object> searchRsList,
			List<TblJumpMchtInf> rsList) {
		
		if(searchRsList != null && searchRsList.size()>0){
			Iterator it  = searchRsList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				TblJumpMchtInf mr = new TblJumpMchtInf();
				mr.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				mr.setMerName(Constance.Null2EmptyTrim(obj[1]));
				mr.setContactName(Constance.Null2EmptyTrim(obj[2]));
				mr.setContactPho(Constance.Null2EmptyTrim(obj[3]));
				mr.setCertif(Constance.Null2EmptyTrim(obj[4]));
				mr.setCertifNo(Constance.Null2EmptyTrim(obj[5]));
				mr.setAccount(Constance.Null2EmptyTrim(obj[6]));
				mr.setStatus(Constance.Null2EmptyTrim(obj[7]));
				mr.setRecTm(Constance.Null2EmptyTrim(obj[8]));
				mr.setMccGroup(Constance.Null2EmptyTrim(obj[9]));
//				mr.setMccGroupName(MccGroup.getName((Constance.Null2EmptyTrim(obj[3]))));
				if("0".equals(mr.getStatus()) && !"".equals(mr.getMccGroup())){
					mr.setStatusName("关闭");
				}else if("1".equals(mr.getStatus())){
					mr.setStatusName("开启");
				}else if("0".equals(mr.getStatus()) && "".equals(mr.getMccGroup())){
					mr.setStatusName("待商户操作");
				}
				
				/*if("0".equals(mr.getRemark1()) || "".equals(mr.getRemark1())){
					mr.setRemark1Name("关闭");
				}else if("1".equals(mr.getRemark1())){
					mr.setRemark1Name("开启");
				}else{
					mr.setRemark1Name("");
				}*/
				
				rsList.add(mr);
			}
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_JUMP_MCHT_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (JumpMchtSearchCondition)getSession().getAttribute(SEARCH_SESSION_JUMP_MCHT_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public JumpMchtSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(JumpMchtSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public TblJumpMchtInf getTjm() {
		return tjm;
	}

	public void setTjm(TblJumpMchtInf tjm) {
		this.tjm = tjm;
	}

	public String getOpenMchtCd() {
		return openMchtCd;
	}

	public void setOpenMchtCd(String openMchtCd) {
		this.openMchtCd = openMchtCd;
	}

	public String getOpenStatus() {
		return openStatus;
	}

	public void setOpenStatus(String openStatus) {
		this.openStatus = openStatus;
	}

	public TblJumpMchtInf getDetail() {
		return detail;
	}

	public void setDetail(TblJumpMchtInf detail) {
		this.detail = detail;
	}
	

}
